package com.xyw.his00.controller;
import com.xyw.his00.dto.LoginDTO;
import com.xyw.his00.service.Impl.dbImpl.EmployeeServiceImpl;
import com.xyw.his00.utils.NumberUtils.TokenUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;


@RestController
public class loginController {
    @Resource
    private EmployeeServiceImpl employeeService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @RequestMapping("/login")
    //token====》访问系统锁 有人就不开锁，没人就开锁
    public Map<String,Object> login(
            @RequestParam("realName") String username,
            String password,
            Integer deptId,
            HttpServletResponse response,
            HttpServletRequest request) throws IOException {


        //登录过期
        boolean b1= employeeService.login(username, password, deptId);
        System.out.println(b1);
        //登录成功
        if(b1){
            HashMap<String,Object> hashMap=new HashMap<>();
            hashMap.put("realName",username);
            //判断有没有这个人的token没有建立，有就继续
            //生成对象的token
            hashMap.put("deptId", deptId.toString());
            String token=TokenUtil.getToken(hashMap);
            hashMap.put("token",token);
            //如果这个对象没有token将对象的token存入redis中
            if(redisTemplate.opsForValue().get(username)==null){
            redisTemplate.opsForValue().set(username,new LoginDTO(deptId,username,token));
            redisTemplate.expire(username,10, TimeUnit.MINUTES);
            }else{
                //如果有就判断该用户的token是否过期
                //如果过期就重新生成token
                if(redisTemplate.hasKey(username)){
                    //删除原来的token
                    redisTemplate.delete("username");
                    //重新生成token
                    redisTemplate.opsForValue().set(username,new LoginDTO(deptId,username,token));
                }
            }
            System.out.println("方法执行");
            return hashMap;
        }
        //登录失败
        else {
            //获取当前请求的url,构建返回的完整的登录url其中包括协议、服务器名称、端口号
            String baseUrl=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
             response.sendRedirect(baseUrl+"/login");
            return null;
        }

}
}